package connect

import (
	"encoding/binary"
	"io"
	"net"

	"gitee.com/yutiandou/wdtools/wdlog"
)

//NetNode ..一个网络连接
type NetNode struct {
	ID   uint32
	Conn net.Conn
	// NodeInfo *routing.Node
	NodeName string
	Address  string
	Quit     chan<- uint32
}

//NewNetNode ..为新连接创建一个实体
func NewNetNode(id uint32, conn net.Conn, q chan<- uint32) (netnode *NetNode) {
	netnode = &NetNode{
		ID:   id,
		Conn: conn,
		//NodeInfo: &routing.Node{},
		Quit: q,
	}
	return
}

//Read 持续接受消息
func (n *NetNode) Read(hand map[uint32]ConnPoolHand) {

	for {
		buf := make([]byte, 8)
		_, err := io.ReadFull(n.Conn, buf)
		if wdlog.Error(err) {
			n.Quit <- n.ID
			break
		}
		purpose := binary.LittleEndian.Uint32(buf[:4])
		len := binary.LittleEndian.Uint32(buf[4:])
		if len > 1024 {
			//TODO
		}
		buf = make([]byte, len)
		_, err = io.ReadFull(n.Conn, buf)
		if wdlog.Error(err) {
			n.Quit <- n.ID
			break
		}
		if hangler, ok := hand[purpose]; ok {
			hangler(n, buf)
		}
	}
}

//Write 发送消息
func (n *NetNode) Write(purpose uint32, value []byte) {
	//value, err := json.Marshal(v)
	len := len(value)
	// if wdlog.Error(err) {
	// 	return
	// }
	data := make([]byte, 8)
	binary.LittleEndian.PutUint32(data, purpose)
	binary.LittleEndian.PutUint32(data[4:], uint32(len))
	data = append(data, value...)
	n.Conn.Write(data)
}

func (n *NetNode) Close() {
	n.Conn.Close()
}
